import axios from 'axios';

// 判断token是否失效
function invalid(str) {
  if (str.search(/access_token/) != -1) {
    //token失效去登录
    logins();
  }
}

// 检查token时间
function checkTime(nowTime, url, rToken) {
  if (nowTime - localStorage.getItem("nowTimes") > 60 * 90) {
    // 超过半个小时没有发生请求默认退出 请求成功就去更新一下localStorage.setItem("nowTimes")
    logins()
  } else {
    //验证token还剩下10分钟   更新token
    if (localStorage.getItem("time") - localStorage.getItem("nowTime") < 10 * 60) {
      let _this = this;
      axios
        .post(url, {
          refresh_token: rToken  
        })
        .then(function (res) {
          console.log(res)
          let data = res.data;
          if (data.code == 1) {
            localStorage.setItem("uid", data.data.user.id); //设置uid
            localStorage.setItem("token", data.data.user.token.access_token); //设置access_token
            localStorage.setItem("reToken", data.data.user.token.refresh_token); //设置refresh_token
            localStorage.setItem("time", data.data.user.token.expire_time); //记录token的有效时间
            localStorage.setItem("nowTime", new Date().getTime() / 1000); //记录当前登录的时间
          }
        })
        .catch(function (error) {
          console.log(error);
        });
    }
  }

}

function checkInputValue(val, type) {
  var engAndNumReg = new RegExp("^[A-Za-z0-9]+$");
  var engReg = new RegExp("^[A-Za-z]+$");
  var numReg = new RegExp("^[0-9]+$");
  if (type == "1") {  //数字+英文
    if (!engAndNumReg.test(val)) {
      return 0;
    }
  }
  if(type == "2"){  //英文
    if (!engReg.test(val)) {
      return 0;
    }
  }
  if(type == "3"){  //数字
    if (!numReg.test(val)) {
      return 0;
    }
  }
}


function logins() {
  localStorage.setItem("uid", "");
  localStorage.setItem("token", "");
  localStorage.setItem("reToken", "");
  localStorage.setItem("time", "");
  window.location.href = '#/';
  window.location.reload();
}


export { invalid, checkTime,checkInputValue}